package com.f5tts.controller;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;


import com.alibaba.fastjson2.JSONWriter;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件管理控制类
 */
@RestController //加入到IOC容器中
public class FileController { //关于File的controller类
    @GetMapping("/toUpload")
    public String toUpload(){
        return "upload";
    }
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload, Model model) {
        //默认文件上传成功,并返回状态信息
//        model.addAttribute("uploadStatus", "上传成功！");
        Map<String,String> map=new HashMap<>();
        for (MultipartFile file : fileUpload) {
            //获取文件名以及后缀名 (获取原始文件名)
            String fileName = file.getOriginalFilename();
            //使用UUID + 原始文件名 来生成一个新的文件名
            fileName = UUID.randomUUID()+"_"+fileName;
            //指定文件上传的本地存储目录，不存在则提前创建
//            String dirPath = "E:\\prjs\\f5tts\\tmp\\";
            String dirPath = System.getProperty("user.dir") + File.separator + "tmp" + File.separator;
            File filePath = new File(dirPath);
            if(!filePath.exists()){filePath.mkdirs();}//创建该目录
            try {
                //执行“文件上传”的方法
                System.out.println(dirPath+fileName);
                file.transferTo(new File(dirPath+fileName));
            }
            catch (Exception e) {e.printStackTrace();
                System.out.println(e.getMessage());
                //上传失败，返回失败信息
//                model.addAttribute("uploadStatus","上传失败： "+e.getMessage());
                map.put("code","-1");
                map.put("data",null);
                map.put("msg","上传失败");
                return JSON.toJSONString(map, JSONWriter.Feature.WriteMapNullValue);
            }

        }
        //携带状态信息回调到文件上传页面
        map.put("code","200");
        map.put("data",null);
        map.put("msg","上传成功");
        return JSON.toJSONString(map, JSONWriter.Feature.WriteMapNullValue);
    }

    @PostMapping("/f5audio")
    public String F5Audio(@RequestParam("name") String name,
                               @RequestParam("author") String author) throws IOException {
        System.out.println("name:" + name + " author: " + author);

        Map<String,String> map=new HashMap<>();
        map.put("code","200");
        map.put("data",null);
        map.put("msg","访问成功");
        return JSON.toJSONString(map, JSONWriter.Feature.WriteMapNullValue);
    }

}